from flask_restful import Resource, request
from flask import abort
import logging
from init import redis_store
from utils.post_request import get_datas

logging.getLogger().setLevel(logging.INFO)


# 只封装datas  不认证
class DataResource(Resource):
    def __init__(self):
        addr = request.remote_addr
        logging.info("addrIP:%s" % addr)
        # 二次封装request
        print('get_datas', get_datas())
        self._datas = get_datas()


# 认证+封装datas
class BaseResource(DataResource):

    def __init__(self):
        DataResource.__init__(self)
        self.verfiy_api()

    def verfiy_api(self):
        auth_erre = 'auth fail,please check the auth message(token&user_id)'
        token_userid = request.headers.get('Auth')
        print('token_userid',token_userid)
        token_userid_arr = str(token_userid).split(',')
        print(token_userid_arr)
        if len(token_userid_arr) < 2:
            abort(401, auth_erre)
        token = token_userid_arr[0]
        user_id = token_userid_arr[1]
        token_redis = redis_store.hget('platformLogin', user_id)
        if token_redis and str(token_redis, 'utf-8') == token:
            self._user_id = user_id
            self._token = token
        else:
            logging.warning('auth fail')
            abort(401, auth_erre)
